const { ethers } = require("hardhat");
const fs = require('fs');

/**
 * 部署到测试网络的完整脚本
 * 这个脚本会：
 * 1. 检查网络环境
 * 2. 验证账户余额
 * 3. 部署合约
 * 4. 验证部署
 * 5. 保存部署信息
 * 6. 提供查看链接
 */
async function main() {
    console.log("🚀 开始部署到测试网络...\n");
    
    // 1. 检查网络环境
    const network = await ethers.provider.getNetwork();
    const [deployer] = await ethers.getSigners();
    
    console.log("📊 部署环境信息:");
    console.log(`网络名称: ${network.name}`);
    console.log(`Chain ID: ${network.chainId}`);
    console.log(`部署者地址: ${deployer.address}`);
    
    // 检查是否为本地网络
    if (network.chainId === 31337n) {
        console.log("⚠️  当前为本地网络，如需部署到测试网，请使用:");
        console.log("   npx hardhat run scripts/deploy-to-testnet.js --network sepolia");
        console.log("\n📝 部署到测试网需要:");
        console.log("1. 配置真实的RPC URL");
        console.log("2. 添加有余额的私钥");
        console.log("3. 确保有足够的测试ETH");
        return;
    }
    
    // 2. 检查账户余额
    const balance = await ethers.provider.getBalance(deployer.address);
    const balanceInEth = ethers.formatEther(balance);
    console.log(`部署者余额: ${balanceInEth} ETH`);
    
    if (balance === 0n) {
        console.log("❌ 余额不足！请先获取测试ETH:");
        console.log("   Sepolia水龙头: https://sepoliafaucet.com/");
        console.log("   或其他水龙头服务");
        return;
    }
    
    // 3. 估算部署成本
    console.log("\n💰 估算部署成本:");
    const AuctionNFT = await ethers.getContractFactory("AuctionNFT");
    const deploymentData = AuctionNFT.getDeployTransaction(deployer.address);
    const estimatedGas = await ethers.provider.estimateGas(deploymentData);
    const gasPrice = await ethers.provider.getFeeData();
    const estimatedCost = estimatedGas * gasPrice.gasPrice;
    
    console.log(`预估Gas: ${estimatedGas.toString()}`);
    console.log(`Gas价格: ${ethers.formatUnits(gasPrice.gasPrice, 'gwei')} Gwei`);
    console.log(`预估成本: ${ethers.formatEther(estimatedCost)} ETH`);
    
    if (balance < estimatedCost * 2n) {
        console.log("⚠️  余额可能不足，建议获取更多测试ETH");
    }
    
    // 4. 开始部署
    console.log("\n🔨 开始部署合约...");
    const startTime = Date.now();
    
    const auctionNFT = await AuctionNFT.deploy(deployer.address);
    console.log("📤 部署交易已发送，等待确认...");
    
    await auctionNFT.waitForDeployment();
    const endTime = Date.now();
    
    const contractAddress = await auctionNFT.getAddress();
    const deploymentTx = auctionNFT.deploymentTransaction();
    
    console.log("✅ 合约部署成功!");
    console.log(`📍 合约地址: ${contractAddress}`);
    console.log(`🔗 部署交易: ${deploymentTx.hash}`);
    console.log(`⏱️  部署耗时: ${endTime - startTime}ms`);
    
    // 5. 验证部署
    console.log("\n🔍 验证部署结果:");
    console.log(`合约名称: ${await auctionNFT.name()}`);
    console.log(`合约符号: ${await auctionNFT.symbol()}`);
    console.log(`合约拥有者: ${await auctionNFT.owner()}`);
    console.log(`下一个TokenId: ${await auctionNFT.getNextTokenId()}`);
    
    // 6. 生成区块链浏览器链接
    console.log("\n🌐 区块链浏览器链接:");
    const explorerUrls = getExplorerUrls(network.chainId);
    if (explorerUrls) {
        console.log(`📋 合约地址: ${explorerUrls.base}/address/${contractAddress}`);
        console.log(`📋 部署交易: ${explorerUrls.base}/tx/${deploymentTx.hash}`);
    }
    
    // 7. 保存部署信息
    const deploymentInfo = {
        contractName: "AuctionNFT",
        contractAddress: contractAddress,
        deploymentTx: deploymentTx.hash,
        deployer: deployer.address,
        network: network.name,
        chainId: network.chainId.toString(),
        blockNumber: deploymentTx.blockNumber,
        gasUsed: deploymentTx.gasLimit?.toString(),
        timestamp: new Date().toISOString(),
        explorerUrls: explorerUrls
    };
    
    // 保存到文件
    const fileName = `deployment-${network.name}-${Date.now()}.json`;
    fs.writeFileSync(fileName, JSON.stringify(deploymentInfo, null, 2));
    console.log(`\n💾 部署信息已保存到: ${fileName}`);
    
    // 8. 测试基本功能
    console.log("\n🧪 测试基本功能:");
    try {
        const testTokenURI = "https://example.com/metadata/test.json";
        const mintTx = await auctionNFT.mint(deployer.address, testTokenURI);
        await mintTx.wait();
        
        console.log("✅ NFT铸造测试成功");
        console.log(`🎨 TokenId: 1`);
        console.log(`👤 拥有者: ${await auctionNFT.ownerOf(1)}`);
        console.log(`🔗 铸造交易: ${explorerUrls ? explorerUrls.base + '/tx/' + mintTx.hash : mintTx.hash}`);
    } catch (error) {
        console.log("❌ NFT铸造测试失败:", error.message);
    }
    
    console.log("\n🎉 部署完成!");
    console.log("📋 后续步骤:");
    console.log("1. 在区块链浏览器中查看合约");
    console.log("2. 验证合约源码（可选）");
    console.log("3. 与合约交互测试");
    console.log("4. 集成到前端应用");
}

/**
 * 获取不同网络的区块链浏览器URL
 */
function getExplorerUrls(chainId) {
    const explorers = {
        1n: { name: "Etherscan", base: "https://etherscan.io" },
        11155111n: { name: "Sepolia Etherscan", base: "https://sepolia.etherscan.io" },
        5n: { name: "Goerli Etherscan", base: "https://goerli.etherscan.io" },
        137n: { name: "Polygonscan", base: "https://polygonscan.com" },
        80001n: { name: "Mumbai Polygonscan", base: "https://mumbai.polygonscan.com" }
    };
    
    return explorers[chainId] || null;
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("❌ 部署失败:", error);
        process.exit(1);
    });